package com.supor.aiot.common.base;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Build;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewStub;
import android.widget.RelativeLayout;

import com.android.baseconfig.common.helper.NetObserverManager;
import com.android.baseconfig.common.observer.NetConnectionObserver;
import com.android.baseconfig.common.utils.DialogUtils;
import com.android.baseconfig.common.utils.StatusBarUtil;
import com.supor.aiot.common.R;
import com.supor.aiot.common.app.AppAgent;
import com.supor.aiot.common.databinding.ActivityBaseBinding;
import com.supor.aiot.common.utils.ClassLoaderFixHelper;
import com.supor.aiot.common.utils.ClassUtil;

import androidx.annotation.LayoutRes;
import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.ViewDataBinding;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.ViewModelProvider;

import autodispose2.AutoDispose;
import autodispose2.AutoDisposeConverter;
import autodispose2.androidx.lifecycle.AndroidLifecycleScopeProvider;
import io.reactivex.rxjava3.disposables.CompositeDisposable;
import io.reactivex.rxjava3.disposables.Disposable;


public abstract class BaseMVVMActivity<VM extends AndroidViewModel, SV extends ViewDataBinding>
        extends AppCompatActivity implements NetConnectionObserver {

    // ViewModel
    protected VM viewModel;
    // 布局view
    protected SV bindingView;
    protected View errorView;
    protected View loadingView;
    protected Dialog dialog;
    protected ActivityBaseBinding mBaseBinding;
    protected CompositeDisposable mCompositeDisposable;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        ClassLoaderFixHelper.interceptLifecycleClassloader(this, savedInstanceState);
        super.onCreate(savedInstanceState);
        initBeforSetContent();
        setContentView(resourceId());
        setStatusBar();
        NetObserverManager.getInstance().addNetObserver(this);
        initView();
        initData();
    }

    protected void initBeforSetContent() {

    }

    @Override
    public void setContentView(@LayoutRes int layoutResID) {

        mBaseBinding = DataBindingUtil.inflate(LayoutInflater.from(this), R.layout.activity_base, null, false);
        bindingView = DataBindingUtil.inflate(LayoutInflater.from(this), layoutResID, null, false);

        // content
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        bindingView.getRoot().setLayoutParams(params);
        RelativeLayout mContainer = (RelativeLayout) mBaseBinding.getRoot().findViewById(R.id.container);
        mContainer.addView(bindingView.getRoot());
        getWindow().setContentView(mBaseBinding.getRoot());

        // loadingView = ((ViewStub) findViewById(R.id.vs_loading)).inflate();

        // bindingView.getRoot().setVisibility(View.GONE);
        setTitleBar();
        initViewModel();
        setNoTitle();
        showContentView();
    }

    protected void setStatusBar() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            if (isUseFullScreenMode()) {
                StatusBarUtil.transparencyBar(this);
            } else {
                StatusBarUtil.setStatusBarColor(this, getStatusBarColor());
            }

            if (isUseBlackFontWithStatusBar()) {
                StatusBarUtil.setLightStatusBar(this, true, isUseFullScreenMode());
            }
        }
    }

    protected void setStatusBarColor(boolean isUseBlack) {
        if (isUseFullScreenMode()) {
            StatusBarUtil.transparencyBar(this);
        } else {
            StatusBarUtil.setStatusBarColor(this, getStatusBarColor());
        }

        if (isUseBlack) {
            StatusBarUtil.setLightStatusBar(this, true, isUseFullScreenMode());
        }
    }

    /**
     * 是否设置成透明状态栏，即就是全屏模式
     */
    protected boolean isUseFullScreenMode() {
        return true;
    }

    /**
     * 更改状态栏颜色，只有非全屏模式下有效
     */
    protected int getStatusBarColor() {
        return com.android.baseconfig.R.color.white;
    }

    /**
     * 是否改变状态栏文字颜色为黑色，默认为黑色
     */
    protected boolean isUseBlackFontWithStatusBar() {
        return true;
    }

    protected abstract int resourceId();

    protected void initView() {
    }

    protected void initData() {
    }

    /**
     * 初始化ViewModel
     */
    protected void initViewModel() {
        Class<VM> viewModelClass = ClassUtil.getViewModel(this);
        if (viewModelClass != null) {
            this.viewModel = new ViewModelProvider(this,
                    ViewModelProvider.AndroidViewModelFactory.getInstance(AppAgent.getApp())).get(viewModelClass);
        }
    }

    /**
     * 设置titlebar
     */
    protected void setTitleBar() {
        mBaseBinding.toolBar.setIvLeftOnClickListener(v -> finish());
    }

    @Override
    public void setTitle(CharSequence text) {
        if (mBaseBinding.toolBar.getVisibility() == View.GONE) {
            mBaseBinding.toolBar.setVisibility(View.VISIBLE);
        }
        mBaseBinding.toolBar.setLeftText(text);
    }

    public void setTitle() {
        mBaseBinding.toolBar.setVisibility(View.VISIBLE);
    }

    public void setNoTitle() {
        mBaseBinding.toolBar.setVisibility(View.GONE);
    }

    protected void pageStartLoading() {
        if (loadingView == null) {
            ViewStub viewStub = (ViewStub) findViewById(R.id.vs_loading);
            loadingView = viewStub.inflate();
        }
        if (loadingView != null && loadingView.getVisibility() != View.VISIBLE) {
            loadingView.setVisibility(View.VISIBLE);
        }
        if (bindingView != null && bindingView.getRoot().getVisibility() != View.GONE) {
            bindingView.getRoot().setVisibility(View.GONE);
        }
        if (errorView != null) {
            errorView.setVisibility(View.GONE);
        }
    }

    protected void showContentView() {
        if (loadingView != null && loadingView.getVisibility() != View.GONE) {
            loadingView.setVisibility(View.GONE);
        }
        if (errorView != null) {
            errorView.setVisibility(View.GONE);
        }
        setNoTitle();
        if (bindingView != null && bindingView.getRoot().getVisibility() != View.VISIBLE) {
            bindingView.getRoot().setVisibility(View.VISIBLE);
        }
    }

    protected void showError() {
        if (loadingView != null && loadingView.getVisibility() != View.GONE) {
            loadingView.setVisibility(View.GONE);
        }
        if (errorView == null) {
            ViewStub viewStub = (ViewStub) findViewById(R.id.vs_error_refresh);
            errorView = viewStub.inflate();
            // 点击加载失败布局
            errorView.findViewById(R.id.cl_root).setOnClickListener(v -> {
                pageStartLoading();
                onRefresh();
            });
        } else {
            errorView.setVisibility(View.VISIBLE);
        }
        setTitle();
        if (bindingView != null && bindingView.getRoot().getVisibility() != View.GONE) {
            bindingView.getRoot().setVisibility(View.GONE);
        }
    }

    protected Activity getActivity() {
        return this;
    }

    /**
     * 失败后点击刷新
     */
    protected void onRefresh() {
        int type = AppAgent.getNetworkType();
        if (type == 0 || type == 5) {
            showError();
        } else {
            showContentView();
        }
    }

    public void showLoading(String tips, boolean isCanCancel) {
        if (null != dialog && dialog.isShowing()) {
            try {
                dialog.dismiss();
            } catch (Exception e) {
                e.printStackTrace();
            }
            dialog = null;
        }
        dialog = DialogUtils.createLoadingDialog(this, tips);
        dialog.setCancelable(isCanCancel);
        dialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
        if (!isFinishing()) {
            dialog.show();
        }
    }

    public void showLoading() {
        showLoading("", true);
    }

    public void closeLoading() {
        if (null != dialog && dialog.isShowing()) {
            try {
                dialog.dismiss();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public void addSubscription(Disposable s) {
        if (this.mCompositeDisposable == null) {
            this.mCompositeDisposable = new CompositeDisposable();
        }
        this.mCompositeDisposable.add(s);
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        if (newConfig.fontScale != 1) {
            getResources();
        }
    }

    /**
     * 禁止改变字体大小
     */
    @Override
    public Resources getResources() {
        Resources res = super.getResources();
        Configuration config = new Configuration();
        config.setToDefaults();
        res.updateConfiguration(config, res.getDisplayMetrics());
        return res;
    }

    /**
     * 可复写处理无网络页面
     *
     * @param type {@link com.android.baseconfig.common.utils.NetWorkUtil}
     */
    @Override
    public void updateNetStatus(int type) {
        if (AppAgent.getCurrentActivity() == this) {
            if (type == 0) {
                showError();
            } else {
                showContentView();
            }
        }
    }

    @Override
    public void updateNFCStatus(int state) {

    }

    @Override
    public void updateWifiStatus(int state) {

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        NetObserverManager.getInstance().removeNetObserver(this);
        if (this.mCompositeDisposable != null && !mCompositeDisposable.isDisposed()) {
            // clear 和 dispose的区别是：  disposed = true;
            this.mCompositeDisposable.clear();
        }
    }

    public void removeDisposable() {
        if (this.mCompositeDisposable != null && !mCompositeDisposable.isDisposed()) {
            this.mCompositeDisposable.dispose();
        }
    }

    public <T> AutoDisposeConverter<T> bindDestoryAutoDispose() {
        return AutoDispose.autoDisposable(
                AndroidLifecycleScopeProvider.from(this, Lifecycle.Event.ON_DESTROY)
        );
    }

    private long lastClick;

    /**
     * [防止快速点击]
     *
     * @return
     */
    public boolean passClick() {
        if (System.currentTimeMillis() - lastClick <= 1000) {
            return false;
        }
        lastClick = System.currentTimeMillis();
        return true;
    }

    @Override
    public void startActivity(Intent intent) {
        super.startActivity(intent);
        overridePendingTransition(com.android.baseconfig.R.anim.activity_open_enter, com.android.baseconfig.R.anim.activity_open_exit);
    }

    @Override
    public void startActivityForResult(Intent intent, int requestCode) {
        super.startActivityForResult(intent, requestCode);
        overridePendingTransition(com.android.baseconfig.R.anim.activity_open_enter, com.android.baseconfig.R.anim.activity_open_exit);
    }

    @Override
    public void finish() {
        super.finish();
        overridePendingTransition(com.android.baseconfig.R.anim.activity_close_enter, com.android.baseconfig.R.anim.activity_close_exit);
    }
}
